from flask import Flask,escape,url_for,render_template,request
from setup import niceday
from navigation import geocodes,walking
from weather import all

# central registry ：中央登记中心，负责所有的页面（url\view functions\template...）登记
app = Flask(__name__)

# 1、(必要) url --> 路径
# ***** 不重要 ：装饰器（@装饰器名称.方法）
# 2、(必要)视图函数 view functions
# 函数的概念：没有调用时，不占空间，且不运行

@app.route('/') #路径的 endpoint（终结点）
@app.route('/func_start',methods=['GET','POST'])
def func_start():
     return render_template("func_start.html")

def log_request(req: 'flask_request', res: str) -> None:
    """日志系统"""
    with open('vsearch.log','a') as log:
        print(req.form, req.remote_addr, req.user_agent, res, file=log, sep='|')
        
#登陆注册
@app.route('/login',methods=['GET','POST'])
def login():
     return render_template("login.html")

@app.route('/register',methods=['GET','POST'])
def register():
     return render_template("register.html")

#网站主页
@app.route('/index',methods=['GET','POST'])
def index():
     return render_template("index.html")

#幸运占卜
@app.route('/lucky',methods=['GET','POST'])
def lucky():
     return render_template("lucky.html")

@app.route('/lucky_result',methods=['GET','POST'])
def lucky_result()->'html':
    phrase = request.form['phrase']
    用户输入的姓名 = request.form['niceday']
    今日运势 = niceday(用户输入的姓名)
    results = str(niceday(用户输入的姓名))
    log_request(request, results)
    return render_template('lucky_result.html',
                            the_phrase=phrase,
                            the_niceday=今日运势)
    log_request(request, phrase)

#南苑导览
@app.route('/navigation',methods=['GET','POST'])
def navigation():
     return render_template("navigation.html")

@app.route('/navigation_result',methods=['GET','POST'])
def navigation_result()->'html':
    key = "eaa6c638561cbb9629a98d39b44f7261"
    出发地 = request.form['origin']
    目的地 = request.form['destination']
    出发地经纬度坐标 = geocodes(key, 出发地)
    目的地经纬度坐标 = geocodes(key, 目的地)
    步行路线 = str(walking(key,出发地经纬度坐标,目的地经纬度坐标))
    results = 步行路线
    log_request(request, results)
    return render_template("navigation_result.html",
                            the_origin=出发地,
                            the_destination=目的地,
                            the_walking=步行路线)
    log_request(request,the_walking)
#天气查询
@app.route('/weather',methods=['GET','POST'])
def weather():
     return render_template("weather.html")

@app.route('/weather_result', methods=['GET','POST'])
def weather_results()->'html':
    key = 'eaa6c638561cbb9629a98d39b44f7261'
    city = request.form['city']
    result_humidity = str(all(key, city,output='JSON', extensions='base')['humidity'])
    result_winddirection = str(all(key, city, output='JSON', extensions='base')['winddirection'])
    result_windpower = str(all(key, city, output='JSON', extensions='base')['windpower'])
    result_temperature = str(all(key, city, output='JSON', extensions='base')['temperature'])
    result_weather = str(all(key, city, output='JSON', extensions='base')['weather'])
    result_reporttime = str(all(key, city, output='JSON', extensions='base')['reporttime'])
    return render_template('weather_result.html',
                           the_city=city,
                           humidity=result_humidity,
                           winddirection=result_winddirection,
                           windpower=result_windpower,
                           temperature=result_temperature,
                           weather=result_weather,
                           reporttime=result_reporttime,
                           )



#日志系统
@app.route('/viewlog')
def view_the_log():
    """display the contents of thr log file as a html table"""
    contents = []
    with open('vsearch.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    len(contents)
    titles = ('From Data','Remote_addr','User_agent','Results')
    return render_template('viewlog.html',
                           the_title='日志系统后台',
                           the_row_title=titles,
                           the_data=contents)

#变量规则
@app.route('/user/<username>',methods=['POST'])
def show_user_profile(username):
    # show the user profile for that user
    return 'hello %s' % escape(username)

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id



if __name__ == '__main__':
    app.run(host='127.0.0.1',port='8888',debug=True)
